home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 590 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.0 KB

  1. Path: ix.netcom.com!netnews
  2. From: miker3@ix.netcom.com (Mike Rubenstein)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: gets() question
  5. Date: Sun, 07 Jan 1996 16:54:10 GMT
  6. Organization: Netcom
  7. Message-ID: <30eff9c3.137769152@nntp.ix.netcom.com>
  8. References: <4cosgf$rir@newsbf02.news.aol.com>
  9. NNTP-Posting-Host: ix-dc7-25.ix.netcom.com
  10. X-NETCOM-Date: Sun Jan 07  8:53:58 AM PST 1996
  11. X-Newsreader: Forte Agent .99c/16.141
  12.  
  13. simpsondg@aol.com (SimpsonDG) wrote:
  14.  
  15. |>Can any of you C gurus out there help me with this?  I have a
  16. problem with
  17. |>gets() that I don't understand.  The program below will successfully
  18. input
  19. |>the string s[0], but will simply ignore the gets() that inputs s[1]
  20. and
  21. |>goes on to ask for i[1].  What's the deal?  A little experimenting
  22. seems
  23. |>to indicate that the problem arises when I have a gets() following a
  24. |>scanf() -- e.g., a program using only gets() or only scanf() works
  25. fine.
  26. |>
  27. |>David Simpson
  28. |>
  29. |>--------------------------------------------------------------------------
  30. |>-------------------
  31. |>
  32. |>#include "stdio.h"
  33. |>
  34. |>void main(void)
  35. |>{
  36. |>   int i[5];
  37. |>   char s[3][10];
  38. |>
  39. |>   printf ("Enter s[0]:  ");
  40. |>   gets (s[0]);
  41. |>
  42. |>   printf ("Enter i[0]]:  ");
  43. |>   scanf ("%d",&i[0]);
  44. |>
  45. |>   printf ("Enter s[1]:  ");
  46. |>   gets (s[1]);                  /* this gets() doesn't wait for
  47. input */
  48. |>
  49. |>   printf ("Enter i[1]]:  ");
  50. |>   scanf ("%d",&i[1]);
  51. |>}
  52.  
  53. scanf() reads characters that match the format item.  When it hits one
  54. that doesn't fit, it pushes it back on the input and continues.  Here
  55. you are entering an integer followed by a newline.  The newline gets
  56. pushed back, so the first think the next gets() sees is the end of the
  57. line.  Since no more input is required, it returns immediately.
  58.  
  59. Note also that it's a very good idea not to use gets() since there is
  60. no protection against overrunning the array.  fgets() is much safer.
  61.  
  62. The easiest way to handle this problem is to use fgets() to read each
  63. line and then use sscanf() or some other function to get numeric data.
  64.  
  65.  
  66. Michael M Rubenstein
  67.